import RouterView from "@/router";
import { AppstoreOutlined, HomeOutlined } from "@ant-design/icons";
import { Avatar, Button, Col, Menu, MenuProps, message, Popover, Row } from "antd";
import { FC, ReactNode, useEffect, useState } from "react";
import { RouteComponentProps } from "react-router-dom";
import "./index.scss";
import avatar from "../assets/images/avatar.png";
const menus: MenuProps["items"] = [
  {
    label: "首页",
    key: "home",
    icon: <HomeOutlined />,
  },
  {
    label: "任务管理",
    key: "task",
    icon: <AppstoreOutlined />,
    disabled: false,
  },
];

interface IIndexPageProps extends RouteComponentProps {
  // 子路由配置
  routes: [];
}

const IndexPage: FC<IIndexPageProps> = ({ history, routes, location }) => {

  /** 将memu的默认选中key的值放在useEffect函数中设置 */
  const [current, setCurrent] = useState<string>("");

  useEffect(() => {
    /** 重定向到/home */
    if (location.pathname === "/") {
      history.push("/home");
    }
    /** 初始化menu选中为home */
    setCurrent("home");
    const isLogin = localStorage.getItem("isLogin");
    if (!isLogin) {
      history.push("/login");
    }
    if (history.location.pathname.includes("task")) {
      if (current !== "task") {
        setCurrent("task");
      }
    }
    const historyListen = history.listen((location: any) => {
      const { pathname } = location;
      if (pathname.includes("task")) {
        setCurrent("task");
      }
      if (location.pathname === "/") {
        history.push("/home");
      }
    });
    return () => {
      /**组件销毁时，取消路由监听*/
      console.log(222)
      historyListen && historyListen();
    };
  }, []);

  const onClick: MenuProps["onClick"] = (e) => {
    // 这里是一个优化点，更新menu key的时候，需要判断下是否改变了
    if (current !== e.key) {
      setCurrent(e.key);
      history.push(`/${e.key}`);
    }
  };

  const logout = () => {
      localStorage.removeItem("isLogin");
      message.success("退出成功！")
      history.push("/login")
  } 

  /** 头像上的气泡卡片内容：退出登录组件 */
  const LogoutComp=():ReactNode => {
      return (
        <div 
          onClick={logout} 
          style={{textAlign:"center",cursor:"pointer"}}>
          退出登录
        </div>
      )
  }

  return (
    <div className="home-page">
      <div className="home-menu">
        <Row align="middle">
          <Col span={22}>
            <Menu
              onClick={onClick}
              selectedKeys={[current]}
              mode="horizontal"
              items={menus}
            />
          </Col>
          <Col span={2}>
            {/* 气泡卡片 */}
            <Popover
              placement="bottom"
              content={LogoutComp}
              trigger="click"
            >
              <Avatar src={avatar} />
            </Popover>
          </Col>
        </Row>
      </div>
      {/* 渲染子路由 */}
      <div className="home-content">
        <RouterView routes={routes} />
      </div>
    </div>
  );
};

export default IndexPage;
